package com.xxwy.api.resthandlers;

import com.xxwy.api.bean.MethodInfo;
import com.xxwy.api.bean.ServerInfo;
import com.xxwy.api.interfaces.RestHandler;
import org.reactivestreams.Publisher;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @author xxwy
 */
public class WebClientRestHandler implements RestHandler {

    private WebClient webClient;

    @Override
    public void init(ServerInfo serverInfo) {
        this.webClient = WebClient.create(serverInfo.getUrl());
    }

    /**
     * 处理请求
     * @param methodInfo
     * @return
     */
    @Override
    public Object invokeRest(MethodInfo methodInfo) {
        //处理请求
        Object result = null;
        //发送请求
        WebClient.RequestBodySpec request = this.webClient
                .method(methodInfo.getMethod())
                .uri(methodInfo.getUrl())
                .accept(MediaType.APPLICATION_JSON);
        //判断是否带了body
        WebClient.ResponseSpec retrieve;
        if(methodInfo.getBody()!= null) {
            retrieve = request.body(methodInfo.getBody(), methodInfo.getBodyElementType()).retrieve();
        }
        else {
            retrieve = request.retrieve();
        }

        //处理异常
        retrieve.onStatus(status ->status.value() == 404,response->Mono.just(new RuntimeException("NOT FOUND")));

        //判断返回类型类型
        if(methodInfo.isReturnFlux()){
            result = retrieve.bodyToFlux(methodInfo.getReturnElementType());
        }else{
            result = retrieve.bodyToMono(methodInfo.getReturnElementType());
        }
        return result;
    }
}
